package com.xm.clj.underserver.controller;

import com.alibaba.fastjson.JSON;
import com.xm.clj.underserver.bean.GetMessage;
import com.xm.clj.underserver.bean.StartInfo;
import com.xm.clj.underserver.utils.AsyncTask;
import com.xm.clj.underserver.webSocket.OneToManyWebSocket;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet(name = "start",urlPatterns = "/startBtn")
public class StartGameController extends HttpServlet {

    @Autowired
    AsyncTask asyncTask;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        InputStream is = req.getInputStream();
        String str = IOUtils.toString(is,"UTF-8");
        System.out.println("str: "+str);
        String path = req.getServletPath();
        if (path.equals("/startBtn")){
            System.out.println("create a game");
            // 生成一轮游戏
            JSONObject jsonObject = JSONObject.fromObject(str);
            StartInfo startInfo = (StartInfo) JSONObject.toBean(jsonObject,StartInfo.class);
            OneToManyWebSocket.roomOwner.put(startInfo.getRoomId(),startInfo.getOwner());
            System.out.println("info: "+startInfo.getRoomId());
            asyncTask.startGameTask(startInfo);
            GetMessage getMessage = new GetMessage();
            resp.getWriter().write(JSON.toJSONString(getMessage));
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPut(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doDelete(req, resp);
    }
}
